package com.group.voting_system.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Author: xyf
 * @Date: 2019/6/21 21:28
 */
public class ImgUtil {
    public static void resizeImage(File file){

        BufferedImage src = null;

        //重新调整大小
        try {
            src = ImageIO.read(file);
            src = Thumbnails.of(src).size(413, 626).keepAspectRatio(false).asBufferedImage();
            //检测图片大小是否大于300kb，如果大于300kb就要压缩
            while (file.length() / 1024 > 50  && file.length() / 1024 > 30) {
                src = Thumbnails.of(src).scale(1f).outputQuality(0.25f).asBufferedImage();
                ImageIO.write(src, "jpg", file);
                src = ImageIO.read(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ImageIO.write(src, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
